//index.js
//获取应用实例
const app = getApp()

import WXAPI from './../../wxApi/main.js'
import store from './../../utils/store'

Page({
  data: {
    hasUserInfo: wx.getStorageSync('hasUserInfo') || false,
    hasMobileInfo: wx.getStorageSync('hasMobileInfo') || false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    if (!wx.getStorageSync('hasUserInfo')) {
      console.log("这逼公开信息没授权")
    }else if (!wx.getStorageSync('hasMobileInfo')) {
      console.log("这逼个人信息没授权")
    }else{
      console.log("已经授权了")
      store.setItem("modalName",null)
      wx.switchTab({
        url: '/pages/home/home',
        success: function (e) {
          var page = getCurrentPages().pop();
          if (page == undefined || page == null) return;
          page.onLoad();
        }
      })

    }
  },
  onShow: function () {

  },

  // 允许订阅
  receiveMsg: function () {
    wx.requestSubscribeMessage({
      tmplIds: ['Cq5KLIked9oxeOTZF5QwsWQGgGoTZwn2ZMq8s_alfcs','wIvWxG37pVd668yjg2KFqHh6KIoASdCUFpk8fmP9ZDI'],
      success(res) {
        console.log("授权成功", res)
        let requestMobileDto = wx.getStorageSync("requestMobileDto")
        let smallRoutineLoginDto = wx.getStorageSync("smallRoutineLoginDto")
        wx.showLoading({
          title: '登录中',
        })
        // 登录
        wx.login({
          success: resp => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            // wx.setStorageSync("code", res.code)
            smallRoutineLoginDto.code = resp.code
            // 登录接口
            WXAPI.login({
              userName: smallRoutineLoginDto.userInfo.nickName,
              requestMobileDto: requestMobileDto,
              smallRoutineLoginDto: smallRoutineLoginDto
            }).then(function (res) {
              wx.hideLoading()
              if (res.code == 200) {
                store.setItem("modalName","")
                store.setItem("userInfo",res.data)
                wx.switchTab({
                  url: '/pages/home/home',
                  success: function (e) {
                    var page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.onLoad();
                  }
                })
              }else{
                wx.showModal({
                  title: '提示',
                  cancelColor: 'cancelColor',
                  content:'网络异常，请重试',
                  showCancel: false,
                  success: res=>{
                    if (res.confirm) {
                      wx.clearStorage()
                      store.clear()
                      wx.reLaunch({
                        url: '/pages/index/index',
                      })
                    }
                  }
                })
              }
            }).catch(function (e) {
              console.log(e)
                wx.showToast({
                  title: e.msg,
                  icon: 'none'
                })
            })
          }
        })

      
      },
      fail(res) {
        console.log("授权失败", res)
      }
    })
  },

  /*点击获取个人信息 */
  getUserInfo: function (e) {
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      wx.showModal({
        title: '温馨提示',
        content: '亲,为了不影响您的正常使用，请同意授权',
      })
      return
    }
    wx.setStorageSync("smallRoutineLoginDto", e.detail)
    wx.downloadFile({
      url: e.detail.userInfo.avatarUrl, // 网络返回的图片地址
      fail: function (err) {
        console.log(err)
      },
      success: function (res) {
        // console.log(res.tempFilePath, "下载路径");
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            // console.log(res.savedFilePath,"保存路径");
            wx.setStorageSync("photoPath", res.savedFilePath)
          }
        })
      }
    })

    wx.setStorageSync("hasUserInfo", true)
    this.setData({
      hasUserInfo: true
    })
  },
  
  /*点击获取手机号码按钮*/
  getPhoneNumber: function (e) {
    var that = this;
    wx.checkSession({
      success: function (res) {
        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
          wx.showModal({
            title: '温馨提示',
            content: '亲,为了不影响您的正常使用，请同意授权',
          })
          return
        }
        wx.setStorageSync("requestMobileDto", e.detail)
        wx.setStorageSync("hasMobileInfo", true)
        that.setData({
          hasMobileInfo: true
        })
       
        
      }
    });
  }
})